package controler;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.SanphamModel;
import model.UpfileModel;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.GetCnn;
import dao.common;

/**
 * Servlet implementation class quanglyquangcao
 */
@WebServlet("/quanglyquangcao")
public class quanglyquangcao extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public quanglyquangcao() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException{
    	HttpSession session = request.getSession();
    	common cm = new common();   	
    	if(cm.checkquyen(session)== false){
    		response.sendRedirect("listDanhmuc");
    	}
    	else{
    		String saveFilepath = "" ;
	    	Connection cnn = GetCnn.getCnn();
			Statement stat = cnn.createStatement();
			
			
			
			UpfileModel umodel = new UpfileModel();
			Hashtable params = new Hashtable();
			
			if (!ServletFileUpload.isMultipartContent(request)) {
				// if not, we stop here
				PrintWriter writer = response.getWriter();
				writer.println("Error: Form must has enctype=multipart/form-data.");
				writer.flush();
				return;
			}
			else{
				DiskFileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				List items = null;
				try {
					items =upload.parseRequest(request);
				} catch (FileUploadException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Iterator iter = items.iterator();
				String fileName = null;
				
				while(iter.hasNext()){
					FileItem item = (FileItem)iter.next();
					if(item.isFormField()){
						params.put(item.getFieldName(), item.getString());
					}
					else{
						String itemName = item.getName();
						fileName = itemName.substring(itemName.lastIndexOf("\\")+1);
						String RealPath =getServletContext().getRealPath("/");
						RealPath = umodel.getpath(RealPath) +fileName ;
						saveFilepath = umodel.getfilePath(RealPath);
						File saveFile = new File(RealPath);
						try {
							item.write(saveFile);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
	
	
	    	String option = request.getParameter("option");
	    	String tenqc =(String) params.get("tenqc");
	    	tenqc = new String(tenqc.getBytes("8859_1"),"UTF8");
	    	String congty = (String) params.get("congty");
	    	congty = new String(congty.getBytes("8859_1"),"UTF8");
	    	String urlhinh = saveFilepath;
	    	String sSQL ="";
	    	if(option.equals("addnew")){
	    		int maqc = 0;
	    		SanphamModel model = new SanphamModel();
	    		maqc = model.getTotalRows("select * from quangcao") + 1;
	    		sSQL = "insert into quangcao VALUES('"+maqc+"',N'"+tenqc+"',N'"+congty+"','"+urlhinh+"',1)";
	    		stat.executeUpdate(sSQL);
	    	}
	    	
	    	response.sendRedirect("adminquangcao");
    	}
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
